#include "PptpMessage.h"

PptpMessage::PptpMessage(QObject *parent)
    : QObject{parent}
{
}
PptpMessage::PptpMessage(const PptpMessage &pptpMessage, QObject *parent) : QObject{parent}
{
    this->path = pptpMessage.path;             // 路径
    this->parameters = pptpMessage.parameters; // 参数体
    this->files = pptpMessage.files;           // 文件列表
}
void PptpMessage::setPath(QString path)
{
    this->path = path;
}
QString PptpMessage::getPath()
{
    return path;
}
void PptpMessage::setParameters(QJsonObject parameters)
{
    this->parameters = parameters;
}
QJsonObject PptpMessage::getParameters() const
{
    return parameters;
}
void PptpMessage::addFile(const QString &filename, const QByteArray &file)
{
    files.insert(filename, file);
}
QHash<QString, QByteArray> PptpMessage::getFiles() const
{
    return files;
}
QByteArray PptpMessage::wrapJson() const
{
    QJsonObject messageJson;
    messageJson["path"] = path;
    messageJson["parameters"] = parameters;
    QJsonArray filesArrayJson;

    for (auto it = files.begin(); it != files.end(); ++it)
    {
        QJsonObject fileJson;
        fileJson["filename"] = it.key();
        fileJson["content"] = QString::fromLatin1(it.value().toBase64());
        filesArrayJson.append(fileJson);
    }

    messageJson["files"] = filesArrayJson;
    return QJsonDocument(messageJson).toJson(QJsonDocument::Compact);
}
void PptpMessage::parseJson(const QByteArray &data)
{
    QJsonDocument messageJsonDoc = QJsonDocument::fromJson(data);
    QJsonObject messageJson = messageJsonDoc.object();
    path = messageJson["path"].toString();
    parameters = messageJson["parameters"].toObject();
    QJsonArray filesArrayJson = messageJson["files"].toArray();
    for (const QJsonValue &value : filesArrayJson)
    {
        QJsonObject fileJson = value.toObject();
        QString filename = fileJson["filename"].toString();
        QByteArray fileContent = QByteArray::fromBase64(fileJson["content"].toString().toLatin1());
        files.insert(filename, fileContent);
    }
}
void PptpMessage::clear()
{
    path.clear();
    parameters = QJsonObject();
    files.clear();
}
